package hu.rsc.feeds.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DispatcherServletEnNews extends HttpServlet {

    private static final long serialVersionUID = 1268908910096781069L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	service(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
	service(request, response);
    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) {
	String agent = request.getHeader("user-agent").toLowerCase();
	if (agent != null && agent.contains("oogle")) {

	    try {
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String url = "http://rscrssreader.appspot.com/rscrssfeeds/whatisnew?app=rssfeeds&lang=en";

		URL oracle = new URL(url);
		BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

		String inputLine;

		int line = 0;
		while ((inputLine = in.readLine()) != null) {
		    if (line != 0) {
			response.getWriter().print(inputLine);
		    }
		    line++;
		}

		in.close();

	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    //google bot
	} else {
	    try {
		response.sendRedirect("index.html");
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
    }
}
